﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Tulde.Core;
using Tulde.MP3tunes;
using Tulde.MP3tunes.Model;
using WP7.LockerPlayer.ViewModels;

namespace WP7.LockerPlayer
{
    public partial class MainPage : PhoneApplicationPage
    {
        public App MainApplication
        {
            get
            {
                return App.Current as App;
            }
        }
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.MainApplication.RootFrame.Obscured += new EventHandler<ObscuredEventArgs>(RootFrame_Obscured);
            this.MainApplication.RootFrame.Unobscured += new EventHandler(RootFrame_Unobscured);
            // Set the data context of the listbox control to the sample data
            DataContext = MainViewModel.Instance;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);


          

       
        }
        private void ResolveCredentials( )
        {
#if DEBUG
            var d = DefaultCredentials.CreateCredentials();
            d.UserName = "jason.tully@gmail.com";
            d.Password = "jason123";
            SecurityProvider.SetCredentials(d);
#else
      SecurityProvider.RestoreCredentials();

#endif


        }
        private void ToggleProgressBar(bool state)
        {
            this.progressInd.IsIndeterminate = state;
        }

        void RootFrame_Unobscured(object sender, EventArgs e)
        {
            DataContext = MainViewModel.Instance;
        }

        void RootFrame_Obscured(object sender, ObscuredEventArgs e)
        {
            DataContext = MainViewModel.Instance;
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
           
            
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
              
                if (!SecurityProvider.IsAuthenticated)
                {
                    this.ToggleProgressBar(true);
                    this.status.Text = "Authenticating";
                    //we need to log the user in.  But we must all first check to see if there are any cached credentials.  If not, we present the user with a login form.
                    this.ResolveCredentials();
                    if (SecurityProvider.Credentials == null)
                    {
                        this.status.Text = "show login form";
                        //show the login form.
                    }
                    else
                    {
                      
                        MainViewModel.Instance.LoadData(complete =>
                        {
                          
                            //data load is complete, so we should be able to bind the view model.
                            DataContext = MainViewModel.Instance;
                            this.ToggleProgressBar(false);
                            this.status.Text = "";

                            this.artistListBox.DataContext = MainViewModel.Instance.ArtistsGroupedByName;
                            this.albumsList.DataContext = MainViewModel.Instance.AlbumsGroupedByName;
                        }, error =>
                        {

                            this.status.Text = error.Message;
                            this.ToggleProgressBar(false);
                        }, p =>
                        {
                            this.status.Text = p;
                        });

                    }
                }
                else
                {
           
                    if (!MainViewModel.Instance.IsDataLoaded)
                    {
                        MainViewModel.Instance.LoadData(complete =>
                        {

                            //data load is complete, so we should be able to bind the view model.
                            DataContext = MainViewModel.Instance;
                            this.ToggleProgressBar(false);

                        }, error =>
                        {
                            MessageBox.Show(error.Message);
                            this.ToggleProgressBar(false);
                        }, p =>
                        {
                            this.status.Text = p;
                        });
                    }
                }
            }
            else
            {
                this.ToggleProgressBar(false);
            }

          

        }

        private void artistListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MainViewModel.Instance.MediaPlayer.CurrentArtist = this.artistListBox.SelectedItem as ArtistViewModel;
            NavigationService.Navigate(new Uri(Constants.Pages.MediaViewAlbums, UriKind.Relative));
        }

        private void albumsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            AlbumViewModel album = this.albumsList.SelectedItem as AlbumViewModel;
            MainViewModel.Instance.MediaPlayer.CurrentAlbum = album;
            MainViewModel.Instance.MediaPlayer.CurrentArtist = MainViewModel.Instance.Artists.Single(x => x.ArtistId == album.ArtistId);
            MainViewModel.Instance.MediaPlayer.CurrentTracks = new System.Collections.ObjectModel.ObservableCollection<TrackViewModel>();
            MainViewModel.Instance.MediaPlayer.CurrentIndex = 0;
            NavigationService.Navigate(new Uri(Constants.Pages.MedieViewTracks, UriKind.Relative));

        }

        private void playlistsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MainViewModel.Instance.MediaPlayer.CurrentPlaylist = this.playlistsListBox.SelectedItem as PlaylistViewModel;
            MainViewModel.Instance.MediaPlayer.CurrentTracks = new System.Collections.ObjectModel.ObservableCollection<TrackViewModel>();
            MainViewModel.Instance.MediaPlayer.CurrentIndex = 0;
            NavigationService.Navigate(new Uri(Constants.Pages.MediaViewPlaylists, UriKind.Relative));
        }

       
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.logMessage.Text = LogProviderFactory.Instance.Read();
        }

        private void resetBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void SettingsView_OnCacheClear(object sender, EventArgs e)
        {

            MainViewModel.Instance.LoadData(complete =>
            {

                //data load is complete, so we should be able to bind the view model.
                DataContext = MainViewModel.Instance;
                this.ToggleProgressBar(false);
                this.status.Text = "";
            }, error =>
            {

                this.status.Text = error.Message;
                this.ToggleProgressBar(false);
            }, p =>
            {
                this.status.Text = p;
            });
        }
 
    }
}